#include "kernel/types.h"
#include "user/user.h"
#define RE 0
#define WR 1

int main(int argc, char *argv[]){
  // child to parent
  int c2p[2];
  // parent to child
  int p2c[2];
  
  pipe(c2p);
  pipe(p2c);

  int pid = fork();
  // Testing after the "if part" has run, why the "else part" can run
  //printf("pid is %d\n", pid);
  // After testing, we can find that the file has been started twice.
  // But in the printed text, the first pid is 4 then the second is 0.
  // It's different from my mind.
  // process statu
  int exit_statu = 0;

  char buf = 'P';
  
  if(pid < 0){
    fprintf(2, "fork() error \n");
    close(c2p[RE]);
    close(c2p[WR]);
    close(p2c[RE]);
    close(p2c[WR]);
    exit(1);
  } else if(pid == 0){
      close(c2p[RE]);
      close(p2c[WR]);

      if (read(p2c[RE], &buf, sizeof(char)) != sizeof(char)) {
        fprintf(2, "child read() error!\n");
        exit_statu = 1;
      } else {
        fprintf(1, "%d: received ping\n", getpid());
      }
      if (write(c2p[WR], &buf, sizeof(char)) != sizeof(char)) {
        fprintf(2, "child write() error!\n");
        exit_statu = 1;
      }
      close(p2c[RE]);
      close(c2p[WR]);

      exit(exit_statu);
  } else{
       close(c2p[WR]);
       close(p2c[RE]);

       if(write(p2c[WR], &buf, sizeof(char)) != sizeof(char)){
         fprintf(2, "parent write() error!\n");
	 exit_statu = 1;
       }
       if(read(c2p[RE], &buf, sizeof(char)) != sizeof(char)){
         fprintf(2, "parent read() error!\n");
	 exit_statu = 1;
       } else {
         fprintf(1, "%d: received pong\n", getpid());
       }


       close(c2p[RE]);
       close(p2c[WR]);
  
       exit(exit_statu);
  }
}
